
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.BinSetup;
import com.scalar.chiptrack.operations.process.dao.BinSetupDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.users.User;


public class BinSubstituteAction extends ChipTrackAction {
    
   
    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
                                  throws Exception {

        DBTransaction dbTransaction = null;
        boolean success = false;
        HttpSession session = request.getSession (false);
		User user = (User)session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
        HashMap errors = new HashMap();
        String action = request.getParameter ("action");
        
        int processStepId = Integer.parseInt ((String) session.getAttribute ("processStepId"));
        int oldProcessStepId = Integer.parseInt ((String) session.getAttribute ("oldProcessStepId"));
        
        // SAVE ACTION
        if ("save".equalsIgnoreCase (action)) 
        {
        	if(request.getAttribute("formTestBin")==null || !request.getAttribute("formTestBin").equals("true"))
        	{
	            try 
	            {
	                // start transaction 
	                dbTransaction = DBTransaction.getInstance();
	                dbTransaction.begin();
	
	                int trackId = Integer.parseInt ((String) session.getAttribute ("trackId"));
	                String stepName = (String) session.getAttribute ("stepName");
	
	                // Step 1
	                // Save substitutable bin information
	                BinSetupDAO.storeBinSubstitutions (dbTransaction, processStepId, getSubstitutableBins (request));
	
	                // Step 2
	                // Update TEST PROCESS TrackID information
	                ProcessTrackDAO.updateTestTrack (dbTransaction, processStepId, trackId, stepName);
	
	                // End transaction
	                success = true;
	            }
	            catch (ScalarException se) {
	                se.getRootCause().printStackTrace();
	                errors.put ("Internal Server Error", "Could not save Substitutable Bin Information");
	                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
	            }
	            finally {
	                // Rollback or Commit the Transaction
	
	                if (success == true) {
	                    dbTransaction.commit();
	                }
	                else {
	                    dbTransaction.rollback();
	                }
	            }
	
	            if (success = false) {  // send the user back to BinSubstitute page
	                return (mapping.findForward ("failure"));
	            }
	            
	            request.setAttribute("baseProductID", session.getAttribute ("baseProductId"));
	
	            session.removeAttribute ("processStepId");
	            session.removeAttribute ("trackId");
	            session.removeAttribute ("stepName");
	            session.removeAttribute ("baseProductId");
	
	            // If sucessful, go to ProcessView page
	            return (mapping.findForward ("processView"));
        	}
        }
        
        
        // VIEW ACTION
        try {
            ArrayList substitutableBinList = null;
            if (oldProcessStepId != -1) {
                substitutableBinList = BinSetupDAO.loadSubstituableBins (oldProcessStepId);
            }
            else {
                substitutableBinList = BinSetupDAO.loadSubstituableBins (processStepId);
            }
            
            request.setAttribute ("substitutableBinList", substitutableBinList);
        }
        catch (ScalarException se) {
            System.out.println ("Exception while loading Substitutable Bin information: " + se.getRootCause());
        }
        
        return (mapping.findForward ("success"));
    }
    
    
	private HashMap getSubstitutableBins (HttpServletRequest request) 
	{
        HttpSession session = request.getSession();
        ArrayList goodBins = (ArrayList) session.getAttribute (SessionKeys.GOOD_BINS);
        session.removeAttribute (SessionKeys.GOOD_BINS);
        
        HashMap binMap = new HashMap();
                
        if (goodBins == null) 
        {
            return binMap;
        }
        
        int size = goodBins.size();
        
        String partNumber = null;
        String[] substBins = null;        
        
        for ( int i = 0; i < size; i++ ) 
        {
            partNumber = ((BinSetup) goodBins.get(i)).getPartNumber();
            substBins = request.getParameterValues(partNumber);
            binMap.put (partNumber, substBins);
        }
        return binMap;
	}
}